#coding=utf-8
from uliweb import expose

#可以省略直接引用
from uliweb import request, error, redirect
from uliweb.form import *

"""
用户信息维护
"""
def __begin__():
    """
    用户验证
    """
    from uliweb import functions
    return functions.require_login()

@expose('/userpost')
class PostData(object):

    #def __begin__(self):
        #"""
        #用户验证
        #"""
        #from uliweb import functions
        #return functions.require_login()
    
    def __init__(self):
        from uliweb.orm import get_model
        self.usermodel = get_model('user')
    
    def user(self):
        """
        返回给jquery easyui的datagride
        
        所有用户的数据
        """
        
        online_user = request.user
        
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))
        
        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)
            
        userdata = {}
        userdata['rows'] = []
        
        if online_user.is_superuser:
            userdata['total'] = self.usermodel.all().count()
            user = {'data':self.usermodel.all().order_by(self.usermodel.c.id).limit(pageSize).offset(content)}
        else:
            userdata['total'] = self.usermodel.filter(self.usermodel.c.id == online_user).count()
            user = {'data':self.usermodel.filter(self.usermodel.c.id == online_user).limit(1)}
        
        for i in user['data']:
                
            #1 超级管理员 0 普通用户
            if i.is_superuser:
                is_superuser = '是'
            else:
                is_superuser = '否' 
                
            # 1正常 0 删除
            if i.deleted:
                deleted = '正常'
            else:
                deleted = '删除'
            
            userdata['rows'].append({"id":i.id,
                             "username":i.username,
                             "nickname":i.nickname,
                             "email":i.email,
                             "last_login":i.last_login,
                             "is_superuser":is_superuser,
                             "mobile":i.mobile,
                             "deleted":deleted
                             })
        #返回json串
        return json(userdata)

##############################################################################################    
    
    def userinfo(self):
        """
        获取非超级管理员用户，提供给combobox
        """
        data = []
        #找出非管理员，并且状态不是删除的用户
        orm_data = {'data':self.usermodel.filter(
            self.usermodel.c.is_superuser == 0
            ).filter(self.usermodel.c.deleted !=0).order_by(self.usermodel.c.id)}
        
        for i in orm_data['data']:
                
            data.append({"id":i.id,
                         "username":i.username,
                         "nickname":i.nickname
                        })

        #返回json串
        return json(data)